/**
  * Created by Joshua Conero(O'Uymas) on 2017/1/14 0014.
  * QQ: 957376074
  * E-mail: Brximl@163.com
  * sql 生成器
  */
package conero.sql
import java.sql.DriverManager
import scala.collection.mutable.ArrayBuffer
class Query (td:String="") extends DBase{
  private var table = td
  private var sqlWhere = ""
  private var buildSql = ""
  private var sqlField = "*"
  // 非查询数据
  private var unSelectJson = Map[String,Any]()

  // 设置字符串标识符
  var columnSombol = ""
  var valueSombol = ""
  setSombol()

  def setSombol(databasetype:String=""):Unit ={
    val dtype = new dbType(databasetype)
    columnSombol = dtype.getColSmb()
    valueSombol = dtype.getValSmb()
  }
  // 链式方法
  // string 条件
  def where(sql:String):this.type ={
    sqlWhere = sql
    this
  }
  // 链式方法
  // map => key -> value
  def where(json:Map[String,Any]):this.type ={
    var whArr = new ArrayBuffer[String]
    for((k,v)<-json){
      whArr += columnSombol+ k + columnSombol + "="+ valueSombol + v + valueSombol
    }
    sqlWhere = whArr.mkString(" and ")
    this
  }
  // 数据字段
  def field(fieldArray:Array[String]):this.type ={
    sqlField = fieldArray.mkString(columnSombol+","+columnSombol)
    sqlField = columnSombol + sqlField + columnSombol
    this
  }
  def field(fieldString:String):this.type = {
    sqlField = fieldString
    this
  }
  // SQL数据 -> 数据库字段- 字段值
  def data(json:Map[String,Any]):this.type  ={
    unSelectJson = json
    this
  }
  // 查询语句
  def select():String ={
    buildSql =  "select " + sqlField + " from " + table + " "+ sqlWhere
    buildSql
  }
  // 更新语句
  def update(data:Map[String,Any]=null):String ={
    val vdata = if(data.isEmpty) unSelectJson else data
    var attrs = new ArrayBuffer[String]()
    for((k,v) <- vdata){
      attrs += columnSombol + k + columnSombol + " = "+ valueSombol + v + valueSombol
    }
    buildSql = "update "+ attrs.mkString(",") + table + sqlWhere
    buildSql
  }
  // 删除语句
  def delete():String = {
    buildSql = "delete from " + table + sqlWhere
    buildSql
  }
  // 新增语句
  def insert(data:Map[String,Any]=null):String ={
    val vdata = if(data.isEmpty) unSelectJson else data
    var clist = new ArrayBuffer[String]()
    var vlist = new ArrayBuffer[String]()
    for((k,v)<- vdata){
      clist += columnSombol + k + columnSombol
      vlist += valueSombol + v + valueSombol
    }
    buildSql = "insert into "+table+"("+ clist.mkString(",") +") values ("+ vlist.mkString(",") +")"
    buildSql
  }
  // 原生sql
  def query(sql:String):String = {
    buildSql = sql
    buildSql
  }
  // 执行SQL 语句 即链接 Execute 类
  def execute():Execute = {
    Class.forName(driver)
    val con = DriverManager.getConnection(dsn,username,password)
    val dbRun = new Execute(con)
    dbRun.setSQL(buildSql)
  }
}
